<template>
    <div class="warpper-box">
        <div class="inner_box">
            <form-create 
            v-model="params.fApi" 
            :rule="params.rule" 
            :option="params.option" 
            @btn-search-click="loadList(true)" 
            @btn-add-click="add(true)"
            @btn-news-batch-click="delBatchNews" 
            @btn-reset-click="reset"/>
            <website-list
            :key="keys"
            :tableData="tables.tableData" 
            :tableLabel="tables.tableLabel" 
            :models="tables" 
            @on-search-click="loadList"
            @on-selection-click="selectionChange"
            @on-enable-click="enable"
            @on-edit-click="add"
            @on-del-click="del"
            />
            <el-dialog :title="form.title" :visible.sync="form.visible" :width="form.width" :close-on-click-modal="false">
                <el-form :model="ruleForm" ref="ruleForm" :inline="false" size="small">
                    <el-form-item label="封面图" prop="coverImage" :rules="[{required:true, message: '请上传封面图', trigger: 'change'}]">
                       <!--  <el-upload
                        class="avatar-uploader"
                        v-model="ruleForm.coverImage"
                        action="#"
                        accept="image/*"
                        :show-file-list="false"
                        :auto-upload="false"
                        :on-change="onChangeFile"
                        :before-upload="beforeAvatarUpload"> -->
                        <el-upload 
                        class="avatar-uploader"
                        v-model="ruleForm.coverImage" 
                        accept="image/*"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload" 
                        action="#" 
                        :http-request="onChangeFile" >
                            <img v-if="coverImage" :src="coverImage" class="avatar">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div style="margin-left: 20px;">
                                <p style="margin: 0;">只能上传jpg，png，jpeg文件</p>
                                <p style="margin: 0;">图片大小1M以内</p>
                                <p style="margin: 0;">图片高224 宽402 单位像素</p>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="启用/禁用" prop="statusFlag" :rules="[{required:true, message: '请选择状态', trigger: 'bulr'}]">
                        <el-radio-group v-model="ruleForm.statusFlag">
                            <el-radio :label="'1'">启用</el-radio>
                            <el-radio :label="'2'">禁用</el-radio>
                          </el-radio-group>
                    </el-form-item>
                    <el-form-item label="新闻标题" prop="title" :rules="[{required:true, message: '请输入新闻标题', trigger: 'bulr'}]">
                        <el-input v-model="ruleForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="新闻详情" prop="content" :rules="[{ required: true, message: '请输入新闻详情', trigger: 'blur' }]">
                        <quill-editor
                        style="display: inline-block;width: 100%;height: 400px;"
                        v-model="ruleForm.content"
                        :options="editorOption"
                      ></quill-editor>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="form.visible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="onFormSubmit('ruleForm')">保存</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
  </template>
  
  <script>
  import { mapGetters, mapActions } from "vuex";
  import { PARAMS_NEWS,LABEL_NEWS,OPTION_INLINE} from "./websiteModel/website_form"
  import websiteList from "./websiteModel/website_model_list"
  import {uploads} from "@/api/common_api"
  import {
      getNewsList,
      newsSave,
      newsDelBatch,
      newsDel,
      newsDisable,
      newsEnable
    } from "@/api/about_api"
  const toolbarOptions = [
 ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
    ['blockquote', 'code-block'],     //引用，代码块
    [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
    [{ 'script': 'sub'}, { 'script': 'super' }],   // 上下标
    [{ 'indent': '-1'}, { 'indent': '+1' }],     // 缩进
    [{ 'direction': 'rtl' }],             // 文本方向
    [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
    [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
    [{ 'font': [] }],     //字体
    [{ 'align': [] }],    //对齐方式
    ["image","link"],
    ["clean"] //清除字体样式
];
const handlers = {
  image: function image() {
    let self = this;
    var fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      fileInput.setAttribute(
        "accept",
        "image/png, image/gif, image/jpeg","image/jpg"
      );
      fileInput.classList.add("ql-image");
      fileInput.addEventListener("change", async function() {
        let file = fileInput.files[0];
        if (!/image\/\w+/.test(file.type)) {
          Message({
            message: "格式错误，请上传png、gif、jpg格式",
            type: "info",
            duration: 5 * 1000
          });
          return false;
        }
        let form = new FormData();
        form.append("resType", fileInput.files[0]);
        const {code,data} = await uploads('news',form);
        let length = self.quill.getSelection(true).index;
        self.quill.insertEmbed(length, "image", `${process.env.VUE_APP_FILE}${data}`);
        self.quill.setSelection(length + 1);
      });
      this.container.appendChild(fileInput);
    }
    fileInput.click();
  }
};
  export default {
    components:{
        websiteList
    },
    data() {
        return {
            keys:0,
            params:{
                fApi:{},
                rule:PARAMS_NEWS,
                option:OPTION_INLINE
            },
            tables:{
                total:0,
                hackReset:true,
                width:'150',
                tableData:[],
                tableLabel: LABEL_NEWS
            },
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions,
                        handlers: handlers
                    }
                },
                theme: "snow"
            },
            ruleForm:{content:'',title:'',coverImage:'',statusFlag:'1'},
            coverImage:'',
            form:{
                id:'',
                title:'新增新闻',
                width:"900px",
                visible:false,
            },
            page:{
                pageNum:1,
                pageSize:10,
            },
            selectionItem:[]
        };
    },
    computed: {
    ...mapGetters(["smsType","uploadType"])
  },
    mounted() {
        this.loadList(true);
        this.$nextTick(()=>{
            this.params.fApi.setValue({"title":""});
        })
    },
    methods: {
        async loadList(formData) {
            let params = {};
            let query = this.params.fApi.bind();
            params.title = query.title;
            if(formData !== undefined && formData.type === 'page'){
                this.page.pageNum = formData.pageNum;
                this.page.pageSize = formData.pageSize;
            }
            if(formData===true){
                this.page.pageNum = 1;
                this.keys++;
            }
            params.pageNum = this.page.pageNum;
            params.pageSize = this.page.pageSize;
            const req = await getNewsList(params);
            if(req.code === 200){
                this.tables.tableData = req.data.list;
                this.tables.tableData.forEach(element => {
                    element.edit = true;
                    element.del = true;
                });
                this.tables.hackReset = false;
                this.$nextTick(()=>{
                    this.tables.hackReset = true;
                });
                this.tables.total = req.data.total;
            }
        },
        async onChangeFile(file,fileList){
            let formData = new FormData();
            formData.append('file', file.file);
            let fileKey = this.uploadType['news']
            let req = await uploads(fileKey,formData);
            if(req.code === 200){
                this.coverImage = `${process.env.VUE_APP_FILE}${req.data}`;
                this.ruleForm.coverImage =`${process.env.VUE_APP_FILE}${req.data}`
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
            const isLt2M = file.size / 1024 / 1024 < 1;
            if (!isJPG) {
            this.$message.error('封面图片只能是 jpeg，png，jpg 格式!');
            }
            if (!isLt2M) {
            this.$message.error('封面图片大小不能超过 1MB!');
            }
            return isJPG && isLt2M;
        },
        //新增编辑
        add(row){
            if(row === true){
                this.ruleForm = {
                    title:'',
                    coverImage:'',
                    content:'',
                    statusFlag:'1'
                };
                this.coverImage = "";
                this.form.id = "";
            }else{
                this.ruleForm = {
                    title:row.title,
                    coverImage:row.coverImage,
                    content:row.content,
                    statusFlag:row.statusFlag
                };
                this.coverImage = row.coverImage;
                this.form.id = row.id;
            }
            this.form.visible = true;
        },
        async onFormSubmit(formName) {
            this.$refs[formName].validate(async(valid) => {
                if (valid) {
                    try {
                        let params = {};
                        if(this.form.id){
                            params.id = this.form.id;
                        }
                        params.title = this.ruleForm.title;
                        params.coverImage = this.ruleForm.coverImage;
                        params.content = this.ruleForm.content;
                        params.statusFlag = this.ruleForm.statusFlag; // 1是启用 2是禁用 默认启用
                        const { code } = await newsSave(params);
                        if(code === 200){
                            this.$message.success('操作成功');
                            this.form.visible = false;
                            this.loadList(true);
                        }
                    } catch (error) {
                        //this.$message.info(JSON.stringify(error));
                    }
                } else {
                    return false;
                }
            });
        },
        //启用禁用
        enable(row){
            let text = row.statusFlag === '1' ? '禁用后，网站将不会展示该条新闻，确认禁用？' : '启用后，网站将展示该条新闻，确认启用'
            this.$confirm(text, "友情提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                let {code} = row.statusFlag === '1' ? await newsDisable(row.id) : await newsEnable(row.id);
                if(code ===200){
                    this.$message.success("操作成功");
                    this.loadList(true);
                }
            }).catch(() => {});
        },
        del(row){
            this.$confirm('删除后不能恢复，确定删除？', "友情提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                let {code} = await newsDel(row.id);
                if(code ===200){
                    this.$message.success("操作成功");
                    this.loadList(true);
                }
            }).catch(() => {});
        },
        selectionChange(itemArr){
            this.selectionItem = itemArr;
        },
        delBatchNews(){
        if(this.selectionItem.length === 0){
            return this.$message.error("请勾选要删除的数据！");
        }
        this.$confirm("确认删除", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
            }).then(async () => {
            let ids = [];
            this.selectionItem.forEach(v=>{
                ids.push(v.id)
            });
            const req = await newsDelBatch(ids);
            if(req.code === 200){
                this.$message.success("操作成功");
                this.selectionItem = [];
                this.loadList(true);
            }
            }).catch(() => {});
        },
        reset(){
            this.params.fApi.resetFields();
            this.loadList(true);
        }
    }
  };
  </script>
  <style>
    .avatar-uploader .el-upload {
        cursor: pointer;
        position: relative;
        overflow: hidden;
        display: flex;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
        text-align: center;
        margin-right: 10px;
    }
  </style>
